package io.github.wppli.webcocket.interceptor;

import io.github.wppli.domain.websocket.service.WebsocketServerService;
import lombok.AllArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Component
@AllArgsConstructor
public class StompChannelInterceptor implements ChannelInterceptor {

    private static final Logger log = LoggerFactory.getLogger(StompChannelInterceptor.class);
    private final WebsocketServerService websocketServerService;

    @Override
    public Message<?> preSend(@NotNull Message<?> message, @NotNull MessageChannel channel) {
        try {
            StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message);
            switch (Objects.requireNonNull(accessor.getCommand())) {
                case CONNECT:
                    websocketServerService.onOpen(accessor);
                    break;
                case DISCONNECT:
                    // 连接断开时触发
                    websocketServerService.onClose();
                    break;
            }
            return message;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}